<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\material;

use app\enum\CommonEnum;
use app\model\ClientCashRateModel;
use app\model\ClientMaterialPicCostModel;
use app\model\KsMaterialPicDailyReportModel;
use app\model\OeMaterialPicDailyReportModel;
use app\model\PicAdvertiserDailyCostModel;
use app\model\PicDailyCostModel;
use app\model\PicModel;
use app\model\PicNinetyCostModel;
use app\model\PicNinetyDailyCostDataModel;
use app\model\PicNinetyDailyCostModel;
use app\model\QqMaterialPicDailyReportModel;
use app\service\BaseService;
use think\Exception;
use think\facade\Db;

class MaterialPicCostService extends BaseService
{
    /**
     * 图片汇总中间表.
     * @param int $mediaId 媒体id
     * @param int $date 日期
     * @param int $num 脚本编号
     * @return bool|void
     */
    public static function getClientMaterialCost(int $mediaId, int $date, int $num)
    {
        $dateStr = date('Y-m-d', strtotime("{$date}"));
        Db::startTrans();
        try {
            if ($mediaId == CommonEnum::OE_MEDIA) {
                $model = new OeMaterialPicDailyReportModel();
            } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                $model = new KsMaterialPicDailyReportModel();
            } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                $model = new QqMaterialPicDailyReportModel();
            }

            $obj = $model->where('stat_date', $date)->field('min(id) as min_id,max(id) as max_id')->findOrEmpty();
            $minId = $obj->getAttr('min_id') ?? 0;
            $maxId = $obj->getAttr('max_id') ?? 0;
            if ($maxId <= 0 || $minId <= 0) {
                exit;
            }

            $count = $maxId - $minId + 1;
            $len = intval(ceil($count / CommonEnum::SHELL_NUM));
            $data = $model->where('stat_date', $date)
                ->field('id,account_id,advertiser_id,client_id,signature,stat_date,cost,is_sync')
                ->limit($num * $len, $len)
                ->select()->toArray();
            if (! empty($data)) {
                foreach ($data as $val) {
                    if ($val['is_sync'] != $model::SYNC_DISABLE) {
                        // 执行过的不再执行
                        continue;
                    }
                    if (! $val['signature']) {
                        // 无md5，不处理
                        continue;
                    }
                    if ($val['cost'] == 0) {
                        $model->where('id', $val['id'])->update(['is_sync' => 1]);
                        continue;
                    }
                    // 查询file_id
                    $fileId = PicModel::where('signature', $val['signature'])->value('file_id');
                    // 查询客户比例
                    $cashRate = ClientCashRateModel::where('client_id', $val['client_id'])
                        ->where('date_time', $date)
                        ->where('media_id', $mediaId)
                        ->value('valid_rate');
                    $cashRate = $cashRate ?: 0;
                    // 计算现金金额
                    if ($mediaId == CommonEnum::QQ_MEDIA) {
                        $val['cost'] = $val['cost'] / 100;  // 广点通单位分
                    }
                    $cashCost = $val['cost'] * $cashRate;

                    if ($fileId) {
                        // 存video_advertiser_daily表
                        $hasVaData = PicAdvertiserDailyCostModel::where('file_id', $fileId)
                            ->where('stat_date', $dateStr)
                            ->where('media_id', $mediaId)
                            ->find();
                        if ($hasVaData) {
                            PicAdvertiserDailyCostModel::where('id', $hasVaData['id'])
                                ->update(['cost' => $cashCost]);
                        } else {
                            $videoAdvertiserData = [
                                'file_id' => $fileId,
                                'media_id' => $mediaId,
                                'advertiser_id' => $val['advertiser_id'],
                                'stat_date' => $dateStr,
                                'cost' => $cashCost,
                            ];
                            PicAdvertiserDailyCostModel::create($videoAdvertiserData);
                        }
                    }

                    // 判断是否已存在
                    $isHas = ClientMaterialPicCostModel::where('stat_date', $date)
                        ->where('client_id', $val['client_id'])
                        ->where('media_id', $mediaId)
                        ->where('signature', $val['signature'])
                        ->find();
                    if ($isHas) {
                        // 已存在加消耗金额
                        ClientMaterialPicCostModel::where('id', $isHas['id'])->inc('cost', (float) $val['cost'])->update();
                        ClientMaterialPicCostModel::where('id', $isHas['id'])->inc('cash_cost', (float) $cashCost)->update();
                    } else {
                        $dataIn = [
                            'client_id' => $val['client_id'],
                            'signature' => $val['signature'],
                            'media_id' => $mediaId,
                            'file_id' => $fileId ? $fileId : 0,
                            'stat_date' => $date,
                            'cost' => $val['cost'],
                            'cash_cost' => $cashCost,
                        ];
                        ClientMaterialPicCostModel::create($dataIn);
                    }
                    // 修改报表状态
                    $model->where('id', $val['id'])->update(['is_sync' => 1]);
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 图片消耗汇总.
     * @param int $date 日期
     * @param int $mediaId 媒体id
     * @param int $fileId 文件id
     * @return array|mixed|string|true
     */
    public static function cachePicCost(int $date, int $mediaId, int $fileId = 0)
    {
        try {
            Db::startTrans();
            $where = [
                ['b.stat_date', '=', $date],
                ['b.media_id', '=', $mediaId],
            ];
            if ($fileId) {
                $where[] = ['a.file_id', '=', $fileId];
            }
            $dateStr = date('Y-m-d', strtotime("{$date}"));
            $date_datas = PicModel::alias('a')
                ->join('habo_client_material_pic_cost b', 'a.signature=b.signature')
                ->where($where)
                ->field('SUM(b.cash_cost) AS sum_cost,a.file_id,a.task_id,a.product_id,b.stat_date')
                ->group('b.signature')
                ->select()->toArray();
            foreach ($date_datas as $dd) {
                $dd['stat_date'] = $dateStr;
                $where = [
                    'file_id' => $dd['file_id'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];

                $data = [
                    'file_id' => $dd['file_id'],
                    'cost' => $dd['sum_cost'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                // 判断是否存在90天起消日记录，不存在则新增
                $ninetyData = PicNinetyCostModel::where('file_id', $dd['file_id'])
                    ->find();
                if ($ninetyData) {
                    // 是否进90天消耗表内
                    if ($ninetyData['start_date'] <= $dd['stat_date'] && $ninetyData['end_date'] >= $dd['stat_date']) {
                        $isHas = PicNinetyDailyCostModel::where($where)->find();
                        if (! $isHas) {
                            PicNinetyDailyCostModel::create($data);
                        } else {
                            PicNinetyDailyCostModel::where('id', $isHas['id'])->update($data);
                        }

                        // 另一种格式
                        $where_s = [
                            'stat_date' => $dd['stat_date'],
                            'file_id' => $dd['file_id'],
                        ];
                        $isHas = PicNinetyDailyCostDataModel::where($where_s)->find();
                        if (! $isHas) {
                            if ($dd['sum_cost'] > 0) {
                                $datas = [
                                    'file_id' => $dd['file_id'],
                                    'stat_date' => $dd['stat_date'],
                                    'cost' => $dd['sum_cost'],
                                ];
                                if ($mediaId == CommonEnum::OE_MEDIA) {
                                    $datas['oe_cost'] = $dd['sum_cost'];
                                } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                                    $datas['ks_cost'] = $dd['sum_cost'];
                                } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                                    $datas['qq_cost'] = $dd['sum_cost'];
                                }
                                PicNinetyDailyCostDataModel::create($datas);
                            }
                        } else {
                            $datas = [];
                            if ($mediaId == CommonEnum::OE_MEDIA) {
                                $datas['oe_cost'] = $dd['sum_cost'];
                                $datas['cost'] = $dd['sum_cost'] + $isHas['ks_cost'] + $isHas['qq_cost'];
                            } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                                $datas['ks_cost'] = $dd['sum_cost'];
                                $datas['cost'] = $dd['sum_cost'] + $isHas['oe_cost'] + $isHas['qq_cost'];
                            } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                                $datas['qq_cost'] = $dd['sum_cost'];
                                $datas['cost'] = $dd['sum_cost'] + $isHas['ks_cost'] + $isHas['oe_cost'];
                            }
                            PicNinetyDailyCostDataModel::where('id', $isHas['id'])->update($datas);
                        }
                    }
                } else {
                    // 新增记录
                    $ninetyData = [
                        'file_id' => $dd['file_id'],
                        'start_date' => $dd['stat_date'],
                        'end_date' => date('Y-m-d', strtotime($dd['stat_date'] . ' +90 days')),
                        'all_cost' => $dd['sum_cost'],
                    ];
                    if ($mediaId == CommonEnum::OE_MEDIA) {
                        $ninetyData['oe_cost'] = $dd['sum_cost'];
                    } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                        $ninetyData['ks_cost'] = $dd['sum_cost'];
                    } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                        $ninetyData['qq_cost'] = $dd['sum_cost'];
                    }
                    $res = PicNinetyCostModel::create($ninetyData);
                    if ($res) {
                        // 是否进90天消耗表内
                        $isHas = PicNinetyDailyCostModel::where($where)->find();
                        if (! $isHas) {
                            PicNinetyDailyCostModel::create($data);
                        } else {
                            PicNinetyDailyCostModel::where('id', $isHas['id'])->update($data);
                        }

                        // 另一种格式
                        $where_s = [
                            'stat_date' => $dd['stat_date'],
                            'file_id' => $dd['file_id'],
                        ];
                        $isHas = PicNinetyDailyCostDataModel::where($where_s)->find();
                        if (! $isHas) {
                            if ($dd['sum_cost'] > 0) {
                                $datas = [
                                    'file_id' => $dd['file_id'],
                                    'stat_date' => $dd['stat_date'],
                                    'cost' => $dd['sum_cost'],
                                ];
                                if ($mediaId == CommonEnum::OE_MEDIA) {
                                    $datas['oe_cost'] = $dd['sum_cost'];
                                } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                                    $datas['ks_cost'] = $dd['sum_cost'];
                                } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                                    $datas['qq_cost'] = $dd['sum_cost'];
                                }
                                PicNinetyDailyCostDataModel::create($datas);
                            }
                        } else {
                            if ($mediaId == CommonEnum::OE_MEDIA) {
                                $datas['oe_cost'] = $dd['sum_cost'];
                                $datas['cost'] = $dd['sum_cost'] + $isHas['ks_cost'] + $isHas['qq_cost'];
                            } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                                $datas['ks_cost'] = $dd['sum_cost'];
                                $datas['cost'] = $dd['sum_cost'] + $isHas['oe_cost'] + $isHas['qq_cost'];
                            } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                                $datas['qq_cost'] = $dd['sum_cost'];
                                $datas['cost'] = $dd['sum_cost'] + $isHas['ks_cost'] + $isHas['oe_cost'];
                            }
                            PicNinetyDailyCostDataModel::where('id', $isHas['id'])->update($datas);
                        }
                    }
                }

                $row = PicDailyCostModel::where($where)->find();
                if (! $row) {
                    PicDailyCostModel::create($data);
                } else {
                    unset($data['file_id'], $data['media_id'], $data['stat_date']);
                    PicDailyCostModel::where('id', $row['id'])->update($data);
                }
            }
            unset($date_datas);
            Db::commit();
            return true;
        } catch (Exception $e) {
            dump($e);
            Db::rollback();
            return self::getError($e->getMessage());
        }
    }
}
